# -*- coding:utf8 -*-

__author__ = 'cosven'

from bson.objectid import ObjectId

from flask import render_template, send_from_directory
from flask import Markup, request, make_response

from blog import app, login_manager, mongo

from blog.controller import plus
import blog.controller.admin as admin
import blog.controller.user as user
import blog.controller.apis as apis



@app.route('/<path:resource>')
def serve_static_resource(resource):
    """
    使用send_static_file之前(和默认的static路径有关,注意和send_from_directory的区别)
    :type resource: string
    """
    return app.send_static_file(resource)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


# pages
@app.route('/', methods=['GET', 'POST'])
def index():
    categories = apis.get_categories()
    blogs = mongo.db.blog.find({'is_share': False}).sort('mod_date', -1).limit(6) # -1: descending, 1 for ascending
    return render_template('home.html', **locals())

@app.route('/test', methods=['GET', 'POST'])
def test():
    return render_template('test.html', **locals())

@app.route('/apis')
def test_api():
    result = apis.get_categories()
    return "ok"

login_manager.login_view = "/login"

@app.route('/home')
def home():
    categories = apis.get_categories()
    blogs = mongo.db.blog.find({'is_share': False}).sort('pub_date', -1).limit(6) # -1: descending, 1 for ascending
    print blogs
    return render_template('home.html', **locals())

@app.route('/robots.txt')
def robots():
    robots_txt = render_template('robots.txt')
    response = make_response(robots_txt)
    response.headers["Content-Type"] = "text/plain"
    return response

@app.route('/google146486250097e986.html')
def google_verify():
    verify = render_template('google146486250097e986.html')
    response = make_response(verify)
    return response


@app.route('/sitemap.xml')
def sitemap():
    """Generate sitemap.xml """
    url_prefix = 'http://www.cosven.com/'
    url_homepage = 'http://www.cosven.com/home'
    pages = [url_homepage]
    # All pages registed with flask apps
    blog_urls = []
    cate_urls = []
    categorys = apis.get_categories()
    if categorys is not None:
        for each in categorys:
            cate_urls.append(url_prefix + 'cate/' + each['id'])

    blogs = apis.get_blogs()
    if blogs is not None:
        for each in blogs:
            blog_urls.append(url_prefix + 'blog/' + str(each['_id']))

    pages.extend(cate_urls)
    pages.extend(blog_urls)
    sitemap_xml = render_template('sitemap.xml', rules=pages)
    response = make_response(sitemap_xml)
    response.headers["Content-Type"] = "application/xml"

    return response

@app.route('/cate/<_id>')
def cate(_id):
    """
    是否是正确的_id，判断是否存在相应的博客种类
    :param _id: 博客分类的_id
    :return:
    """
    try:
        _id = ObjectId(_id)
    except Exception, e:
        return render_template('404.html')
    cate = mongo.db.category.find_one({'_id': _id})
    if cate is not None:
        cate_name = cate['name']
        blogs = mongo.db.blog.find({'category': cate_name})
        categories = apis.get_categories()
        return render_template('home.html', **locals())
    else:
        return render_template('404.html')


app.add_url_rule('/admin/new', view_func=admin.admin_new)
app.add_url_rule('/admin/edit/<_id>', view_func=admin.admin_edit)
app.add_url_rule('/admin/edit/draft/<_id>', view_func=admin.admin_draft_edit)

app.add_url_rule('/login', methods=['GET', 'POST'], view_func=user.login)
app.add_url_rule('/logout', view_func=user.logout)

@app.route('/blog/<_id>')
def blog(_id):
    """
    是否是正确的_id，检测是否村子相应的博客
    :param _id: 博客的数据库_id
    :return:
    """
    bid = _id
    try:
        _id = ObjectId(_id)
    except Exception, e:
        return render_template('404.html')
    blog = mongo.db.blog.find_and_modify(query={'_id': _id}, update={'$inc': {'read_count': 1}})
    categories = apis.get_categories()
    if blog is not None:
        return render_template('blog.html', **locals())
    else:
        return render_template('404.html')

# API
app.add_url_rule('/plus/bing_image', view_func=plus.BingImage.as_view('bing_image'))

if __name__ == '__main__':
    import os, sys

    sys.path.append('..')
    app.run()
